export function didMount() {
    console.log("「页面 JS」：当前页面地址 " + location.href);

    const echartsScriptTag = document.createElement('script');
    echartsScriptTag.src = 'https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js';
    document.head.appendChild(echartsScriptTag);

    const self = this;

    const ddcatSources = [
        { id: "", name: "日常检查-计划统计分析" },
        { id: "ds_mod:763b1b5d-120b-4c58-9b65-bd5ae9ba9d66", name: "日常检查-计划分布" }
    ];

    // 计划分布
    fetchDdcatData(ddcatSources[1].id).then(res => {
        if (res && res.length) {
            loadProgramStatisticsPieChart(self, res);
        } else {
            const mockData = getRandomNum();
            loadProgramStatisticsPieChart(self, mockData);
        }
    });


}



/**
 * 加载计划分析
 */
function loadProgramStatisticsPieChart(self, data) {

    const chartContainer = self.$$("text_9zm6a3").$el;
    const myChart = echarts.init(chartContainer);

    const total = data.reduce((sum, item) => sum + Number(item.deviceNum), 0);

    // 渐变色配置
    const gradientColors = [
        { start: '#85C0FF', end: '#3388FF' }, // 省（市）级
        { start: '#FFD152', end: '#FFAA00' },  // 县级
        { start: '#5CE0B6', end: '#11C79B'} // 市（区）级
    ];
    const createGradient = (index) => {
        const gradient = gradientColors[index % gradientColors.length];
        return new echarts.graphic.LinearGradient(0, 0, 1, 1, [
            { offset: 0, color: gradient.start },
            { offset: 1, color: gradient.end }
        ]);
    };

    const option = {
        legend: {
            orient: 'horizontal',
            right: '10%',
            top: 'center',
            data: data.map(item => item.planType),
            itemWidth: 15,
            itemHeight: 10,
            itemGap: 15,
            formatter: (name) => {
                const item = data.find(d => d.planType === name);
                const percent = total === 0 ? 0 : ((Number(item.planNum) / total) * 100).toFixed(0);
                return `{name|${name}}{value|${item.planNum}}{space| }{percentage|${percent}%}`;
            },
            textStyle: {
                rich: {
                    name: { width: 70, align: 'left' },
                    value: { width: 40, align: 'right' },
                    percent: { width: 40, align: 'right' }
                }
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        series: [
            {
                type: 'pie',
                radius: ['50%', '70%'],
                center: ['40%', '50%'],
                label: { show: false },
                emphasis: { label: { show: false } },
                data: data.map((item, index) => ({
                    name: item.planType,
                    value: Number(item.planNum),
                    itemStyle: {
                        color: createGradient(index)
                    }
                }))
            }
        ],
        graphic: {
            type: 'text',
            left: '40%',
            top: '40%',
            style: {
                text: `{total|${total}}\n{label|备案总数}`,
                textAlign: 'center',
                rich: {
                    total: {
                        fontSize: 26,
                        fontWeight: 700,
                        color: '#223355',
                        lineHeight: 36
                    },
                    label: {
                        fontSize: 16,
                        color: '#6B7A99',
                        lineHeight: 24
                    }
                }
            }
        }
    };

    myChart.setOption(option);
}

/**
 * 从 ddcat 数据源拉取所有数据
 * @returns Promise<数组> - 返回结果数组
 */
function fetchDdcatData(sourceId) {
    const jsonParams = { pageSize: 99999 };
    return api.DATA_SOURCE_EXECUTE(
        sourceId,
        "ddcat",
        [],
        [],
        JSON.stringify(jsonParams)
    ).then(res => {

        if (res && !res.hasError && res.result != null) {
            return res.result;
        } else {
            console.warn("查询失败或数据为空，生成模拟数据");
            // 这里生成模拟数据
            return [];
        }
    });
}


/**
 * 联合情况
 */
function getRandomNum() {
    const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
    return [
        { planType: '省（市）级', planNum: randomBetween(1000, 5000) },
        { planType: '市（区）级', planNum: randomBetween(1000, 3000) },
        { planType: '县级', planNum: randomBetween(800, 1000) },
    ];
}
